﻿using Algorithm.Check;
using Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Algorithm.Check.ExtensionForCRC16;

namespace NewDevice
{
    internal static class ReceivedDataCheck
    {
        public static bool ModbusCRC16Check(byte[] data)
        {
            if (data == null) { return false; }
            if (data.Length < 2) { return false; }
            var checkedData = data.Take(data.Length - 2).WithCRC16(CRC16Type.Modbus).ToArray();
            if (checkedData.SequenceEqual(data.Skip(data.Length - 2).Take(2)))
                return true;
            else
            {
                Mylog.Error(message: $"CRC checked data excepted[{BitConverter.ToString(checkedData).Replace('-', ' ')}] but response[{BitConverter.ToString(data).Replace('-', ' ')}]");
                return false;
            }
        }

        public static Func<byte[], bool> FuncModbusCRC16Check = new Func<byte[], bool>((data) =>
        {
            if (data == null) { return false; }
            if (data.Length < 2) { return false; }
            var checkedData = data.Take(data.Length - 2).WithCRC16(CRC16Type.Modbus).ToArray();
            if (checkedData.SequenceEqual(data))
                return true;
            else
            {
                Mylog.Error($"CRC checked data excepted[{BitConverter.ToString(checkedData).Replace('-', ' ')}] but response[{BitConverter.ToString(data).Replace('-', ' ')}]");
                return false;
            }
        });
    }
}